package com.study.testSpringBoot.mina;

import java.net.SocketAddress;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

public class MinaServerHandler extends IoHandlerAdapter {

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        //业务代码在这里编写处理
        String str = message.toString();
        System.out.println("The message received is [" + str + "]");
        //获取客户端的连接地址
        SocketAddress socketAddress = session.getRemoteAddress();
        System.out.println(socketAddress);
        
        Object obj = session.getAttribute("test");
        System.out.println(obj);
        //响应给对应客户端信息
        session.write("消息已处理，你可以去玩了。。。");
        
        if (str.endsWith("quit")) {
        	//注意：在这里调用close方法之后，只是关闭当前的tcp连接，server端还正常运行，
        	//需要调用IoService的dispose方法才能关闭server端，client端同理
            session.closeNow();
            return;
        }
    }
    
    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
    	// TODO Auto-generated method stub
    	System.out.println("发送数据成功了。。。"+message);
//    	session.write("testSent");
    	super.messageSent(session, message);
    }

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        System.out.println("server session created");
        super.sessionCreated(session);
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        System.out.println("server session Opened");
        super.sessionOpened(session);
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        System.out.println("server session Closed");
        super.sessionClosed(session);
    }
    
}
